//
//  AddSideDataViewController.m
//  fitnessmanage
//
//  Created by wujian on 2018/1/1.
//  Copyright © 2018年 zongquankeji. All rights reserved.
//

#import "AddSideDataViewController.h"
#import "AddSideDataTableViewCell.h"
#import "MOFSPickerManager.h"
#import "CourseClassAlertView.h"
#import "AddSideViewController.h"

@interface AddSideDataViewController ()<UITableViewDelegate,UITableViewDataSource>

@property(nonatomic,weak)UITableView *tableView;

@property(nonatomic,strong)NSMutableArray *dataSource;

@property(nonatomic,strong)NSMutableDictionary *listData;

@property(nonatomic,strong)NoDataView *noDataView;

@property(nonatomic,weak)CommonBtnView *timeBtnView;

@property(nonatomic,weak)CommonBtnView *modelBtnView;

@property(nonatomic,strong)CourseClassAlertView *courseClassView;

@property(nonatomic,strong)NSString *sideId;

@property(nonatomic,assign)BOOL canEdit;

@end

@implementation AddSideDataViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    self.title = @"添加体侧数据";
    
    self.view.backgroundColor = BackGroundColor;
    
    self.canEdit = YES;
    
    UIBarButtonItem *rightButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"确定" style:UIBarButtonItemStylePlain target:self action:@selector(rightBtnClick)];
    [rightButtonItem setTitleTextAttributes:@{NSForegroundColorAttributeName:CSBlackColor,NSFontAttributeName:MidFont} forState:UIControlStateNormal];
    [rightButtonItem setTitleTextAttributes:@{NSForegroundColorAttributeName:CSBlackColor,NSFontAttributeName:MidFont} forState:UIControlStateHighlighted];
    
    self.navigationItem.rightBarButtonItem = rightButtonItem;
    
    [self createSubView];
    
    [self loadData];
    
    self.noDataView = [NoDataView shareInstance];
    
//    [self.noDataView showInView:self.view];
    
    [NotificationCenter addObserver:self selector:@selector(loadData) name:@"ReloadSide" object:nil];
}

-(void)createSubView{
    
    UITableView *tableView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStylePlain];
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.showsVerticalScrollIndicator = NO;
    tableView.estimatedRowHeight = 100;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [tableView registerClass:[AddSideDataTableViewCell class] forCellReuseIdentifier:@"AddSideDataTableViewCell"];
    tableView.backgroundColor = CSClearColor;
    [self.view addSubview:tableView];
    [tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self.view);
    }];
    self.tableView = tableView;
    
    UIView *headView = [[UIView alloc] init];
    headView.backgroundColor = BackGroundColor;
    headView.frame = CGRectMake(0, 0, self.view.width, 135);
    
    CommonBtnView *timeBtnView = [[CommonBtnView alloc] init];
    timeBtnView.titleLabel.text = @"体侧日期";
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSString *dateTime = [formatter stringFromDate:[NSDate date]];
    timeBtnView.choseLabel.text = dateTime;
    timeBtnView.choseLabel.textColor = TFColor;
    timeBtnView.choseBtn.userInteractionEnabled = NO;
    [timeBtnView.choseBtn addTarget:self action:@selector(choseTime)];
    [headView addSubview:timeBtnView];
    self.timeBtnView = timeBtnView;
    [timeBtnView mas_remakeConstraints:^(MASConstraintMaker *make) {
       
        make.top.left.width.mas_equalTo(headView);
    }];
    
    CommonBtnView *modelBtnView = [[CommonBtnView alloc] init];
    modelBtnView.titleLabel.text = @"体侧模板";
    modelBtnView.choseLabel.text = @"选择模板";
    modelBtnView.choseLabel.textColor = PlaceHoldColor;
    
    [modelBtnView.choseBtn addTarget:self action:@selector(choseModel)];
    [headView addSubview:modelBtnView];
    self.modelBtnView = modelBtnView;
    [modelBtnView mas_remakeConstraints:^(MASConstraintMaker *make) {
       
        make.top.mas_equalTo(timeBtnView.mas_bottom);
        make.left.width.mas_equalTo(headView);
    }];
    
    tableView.tableHeaderView = headView;
    
    if (self.bodyDetailDict) {
        
        NSLog(@"%@",self.bodyDetailDict);
        
        NSString *name = [self.bodyDetailDict objectForKey:@"Name"];
        modelBtnView.choseLabel.text = name;
        modelBtnView.choseLabel.textColor = TFColor;
        modelBtnView.choseBtn.userInteractionEnabled = NO;
        
        NSString *addTime = [self.bodyDetailDict objectForKey:@"AddTime"];
        timeBtnView.choseLabel.text = addTime;
        timeBtnView.choseLabel.textColor = TFColor;
        
        NSString *bodyDataDetailID = [self.bodyDetailDict objectForKey:@"BodyDataDetailID"];
        
//        [self loadBodyDetailWithId:bodyDataDetailID];
        
        self.sideId = [NSString stringWithFormat:@"%@",[self.bodyDetailDict objectForKey:@"ID"]];
        
        NSDateComponents *comonent = [NSString getDateDifference:addTime];
        
        if (comonent.day < 1) {
     
            UIButton *deleteBtn = [[UIButton alloc] init];
            deleteBtn.frame = CGRectMake(0, 0, self.view.width, 50);
            [deleteBtn setTitle:@"删除"];
            [deleteBtn addTarget:self action:@selector(delBtnClick)];
            deleteBtn.titleLabel.font = MidBigFont;
            [deleteBtn setTitleColor:CSColorFromRGB(0xff464e)];
            deleteBtn.backgroundColor = CSWhiteColor;
            tableView.tableFooterView = deleteBtn;
        }
        else{
            
            self.canEdit = NO;
        }
    }
    
}


/**
 获取所有体侧模板
 */
-(void)loadData{

    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    
    [MBProgressHUD showMessage:@"加载中..." toView:self.view];
    
    VenueModel *venueModel = [VenueModel venue];
    
    [params setObject:[[NSUserDefaults standardUserDefaults]objectForKey:@"ShopID"] forKey:@"ShopID"];

    [params setObject:[NSString stringWithFormat:@"%d",1] forKey:@"page"];

    [params setObject:[NSString stringWithFormat:@"%d",100] forKey:@"rows"];
    
    [HTTPTool GET:Get_BodyData_ListData parameters:params
     
          success:^(id responseObject){
              
              [MBProgressHUD hideHUDForView:self.view];
              
              if (responseObject && [[responseObject objectForKey:@"Code"] intValue] == 0) {
                  
                  NSMutableArray *resultArray = [responseObject objectForKey:@"rows"];
                  
                  for (NSDictionary *dict in resultArray) {
                      
                      NSString *ID = [dict objectForKey:@"ID"];
                      
                      NSString *name = [dict objectForKey:@"Name"];
                      
                      [self.listData setObject:ID forKey:name];
                  }
                  
              }
              
          }
     
          failure:^(NSError *error){
              
              [self.tableView.mj_header endRefreshing];
              
              [MBProgressHUD hideHUDForView:self.view];
          }];
}


-(void)loadItemWithId:(NSString *)itemId{
    
    
    //Get_BodyData
    
    NSString *url =[NSString stringWithFormat:@"%@/%@",Get_BodyData,itemId];
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    
    [HTTPTool GET:url parameters:params
     
          success:^(id responseObject){
              
              [MBProgressHUD hideHUDForView:self.view];
              
              if (responseObject && [[responseObject objectForKey:@"Code"] intValue] == 0) {
                  
                  NSDictionary *bodyData = [responseObject objectForKey:@"bodyData"];
                  
                  NSString *fieldItems = [bodyData objectForKey:@"FieldItems"];
                  
                  self.dataSource = [NSMutableArray arrayWithArray:[fieldItems JSONValue]];
                  
                  [self.tableView reloadData];
                  
                  self.noDataView = [NoDataView shareInstance];
                  
                  if (self.dataSource.count == 0) {
                      
                      [self.noDataView showInView:self.view];
                  }
                  else{
                      
                      [self.noDataView hideInView:self.view];
                  }
                  
                  [self.view bringSubviewToFront:self.tableView];
                  
                  [self.tableView reloadData];
              }
              
          }
     
          failure:^(NSError *error){
              
              [self.tableView.mj_header endRefreshing];
              
              [MBProgressHUD hideHUDForView:self.view];
          }];
}

#pragma mark 获取体侧数据详情
-(void)loadBodyDetailWithId:(NSString *)itemId{
    
    NSString *url =[NSString stringWithFormat:@"%@/%@",GET_BodyDataDetail,itemId];
    
    
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    
    [HTTPTool GET:url parameters:params
     
          success:^(id responseObject){
              
              [MBProgressHUD hideHUDForView:self.view];
              
              if (responseObject && [[responseObject objectForKey:@"Code"] intValue] == 0) {
                  
                  NSDictionary *bodyData = [responseObject objectForKey:@"bodyDataDetail"];
                  
                  NSString *fieldItems = [bodyData objectForKey:@"Content"];
                  
                  self.dataSource = [NSMutableArray arrayWithArray:[fieldItems JSONValue]];
                  
                  [self.tableView reloadData];
                  
//                  [self.noDataView hideInView:self.view];
              }
              
          }
     
          failure:^(NSError *error){
              
              [self.tableView.mj_header endRefreshing];
              
              [MBProgressHUD hideHUDForView:self.view];
          }];
}



-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.dataSource.count;
}


#pragma mark UITableViewDelegate
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return 0.00001;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    if (section == 0) {
        
        return 50;
    }
    
    return 15;
    
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    if (section == 0) {
        
        UIView *tableHeadView = [[UIView alloc] init];
        tableHeadView.backgroundColor = CSColorFromRGB(0xfaf6eb);
        
        UILabel *titleLabel = [[UILabel alloc] init];
        titleLabel.text = @"体侧数据";
        titleLabel.font = MidFont;
        titleLabel.textColor = CSColorFromRGB(0x0a0a0a);
        [tableHeadView addSubview:titleLabel];
        [titleLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.centerY.mas_equalTo(tableHeadView);
            make.left.mas_equalTo(tableHeadView).offset(10);
        }];
        
        return tableHeadView;
    }
    
    return nil;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
    return nil;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    AddSideDataTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"AddSideDataTableViewCell"];
    
    if (!self.canEdit) {
        
        cell.valueTF.userInteractionEnabled = NO;
    }
    
    NSDictionary *dict = [self.dataSource objectAtIndex:indexPath.row];
    
    cell.unitLabel.text = [NSString stringWithFormat:@"%@(%@)",[dict objectForKey:@"Name"],[dict objectForKey:@"Unit"]];
    
    NSString *value = [dict objectForKey:@"Value"];
    
    if (![value isEmptyString]) {
        
        cell.valueTF.text = value;
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
}

#pragma mark 选择时间
-(void)choseTime{
    
    [self.view endEditing:YES];
    
    __weak typeof(self)weakSelf = self;
    
    [[MOFSPickerManager shareManger] showDatePickerWithTag:122 title:@"选择时间" cancelTitle:@"取消" commitTitle:@"确定" datePickerMode:UIDatePickerModeDate commitBlock:^(NSDate *date) {
        
        NSDateFormatter *dateFormatter=[[NSDateFormatter alloc]init];//创建一个日期格式化器
        
        dateFormatter.dateFormat=@"yyyy-MM-dd";//指定转date得日期格式化形式
        
        weakSelf.timeBtnView.choseLabel.text = [dateFormatter stringFromDate:date];
        
        weakSelf.timeBtnView.choseLabel.textColor = TFColor;
        
    } cancelBlock:^{
        
        
    }];
}


-(void)choseModel{
    
    [self.view endEditing:YES];
    
    
    if (self.listData.allKeys.count == 0) {
        
        CourseClassAlertView *courseClassView = [[CourseClassAlertView alloc] init];
        courseClassView.titleLabel.text = @"选择体侧模板";
        courseClassView.noticeLabel.text = @"暂无体侧模板";
        courseClassView.noticeLabel1.text = @"前往添加体侧模板";
        [courseClassView.addBtn setTitle:@"添加体侧模板"];
        [courseClassView.addBtn addTarget:self action:@selector(addSide)];
        
        [[UIApplication sharedApplication].keyWindow addSubview:courseClassView];
        
        self.courseClassView = courseClassView;
        
        return;
    }
    
    __weak typeof(self)weakSelf = self;
    
    [[MOFSPickerManager shareManger] showPickerViewWithDataArray:self.listData.allKeys tag:15 title:@"选择模板" cancelTitle:@"取消" commitTitle:@"确定" commitBlock:^(NSString *string) {
                
        weakSelf.modelBtnView.choseLabel.text = string;
        
        weakSelf.modelBtnView.choseLabel.textColor = TFColor;
        
        NSString *sideId = [NSString stringWithFormat:@"%@",[weakSelf.listData objectForKey:string]];
        
        weakSelf.sideId = sideId;
        
        [weakSelf loadItemWithId:sideId];
        
    } cancelBlock:^{
        
    }];
}


#pragma mark 右侧按钮点击
-(void)rightBtnClick{
    
    if ([self.sideId isEmptyString]) {
        
        [MBProgressHUD showText:@"请选择体侧模板"];
        
        return;
    }
    
    if (self.dataSource.count == 0) {
        
        [MBProgressHUD showText:@"该模板没数据"];
        
        return;
    }
    
    NSMutableArray *fieldItemArray = [[NSMutableArray alloc] init];
    
    for (int i =0 ; i < self.dataSource.count; i ++) {
        
        NSMutableDictionary *fieldItemDict = [[NSMutableDictionary alloc] init];
        
        NSDictionary *dict = [self.dataSource objectAtIndex:i];
        
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
        
        AddSideDataTableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
        
        NSString *name = [dict objectForKey:@"Name"];
        
        NSString *unit = [dict objectForKey:@"Unit"];
        
        NSString *value = cell.valueTF.text;
        
        if ([value isEmptyString]) {
            
            [MBProgressHUD showText:@"请输入完整内容"];
            
            return;
        }
        
        [fieldItemDict setObject:name forKey:@"Name"];
        [fieldItemDict setObject:unit forKey:@"Unit"];
        [fieldItemDict setObject:value forKey:@"Value"];
        
        [fieldItemArray addObject:fieldItemDict];
    }
            
    [MBProgressHUD showMessage:@"请求中..." toView:self.view];
    
    VenueModel *venueModel = [VenueModel venue];
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    
//    [params setObject:self.venueVipModel.MemberID forKey:@"MemberID"];
//    
//    [params setObject:self.sideId forKey:@"BodyDataID"];
//    
//    [params setObject:[[NSUserDefaults standardUserDefaults] objectForKey:@"ShopID"] forKey:@"ShopID"];
//    
//    [params setObject:[fieldItemArray toJSONString] forKey:@"Content"];
//    
//    [params setValue:[self.bodyDetailDict objectForKey:@"ID"] forKey:@"ID"];
    
    [HTTPTool POSTRaw:Post_BodyDataDetailOperate parameters:params
     
              success:^(id responseObject){
                  
                  [MBProgressHUD hideHUDForView:self.view];
                  
                  if (responseObject && [[responseObject objectForKey:@"Code"] intValue] == 0) {
                      
                      [MBProgressHUD showText:@"操作成功"];
                      
                      [NotificationCenter postNotificationName:@"ReloadSide" object:nil];
                      
                      [self.navigationController popViewControllerAnimated:YES];
                  }
                  
              }
     
              failure:^(NSError *error){
                  
                  [MBProgressHUD hideHUDForView:self.view];
              }];
}

#pragma mark 删除按钮点击
-(void)delBtnClick{
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示"message:@"确定删除?"preferredStyle:UIAlertControllerStyleAlert];
    
    //添加取消到UIAlertController中
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        
    }];
    [alertController addAction:cancelAction];
    
    //添加确定到UIAlertController中
    UIAlertAction *OKAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        //Post_Shop_DeleteShop
        [MBProgressHUD showMessage:@"删除中..." toView:self.view];
        
        NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
        
        NSString *delUrl = [NSString stringWithFormat:@"%@/%@",Post_DeleteBodyDataDetail,[self.bodyDetailDict objectForKey:@"ID"]];
        
        //[params setObject:[self.bodyDetailDict objectForKey:@"ID"] forKey:@"ID"];
        
        [HTTPTool POSTRaw:delUrl parameters:params success:^(id responseObject) {
            
            [MBProgressHUD hideHUDForView:self.view];
            
            if (responseObject && [[responseObject objectForKey:@"Code"] intValue] == 0){
                
                [MBProgressHUD showText:@"删除成功"];
                
                [NotificationCenter postNotificationName:@"ReloadSide" object:nil];
                
                [self.navigationController popViewControllerAnimated:YES];
            }
            else{
                
                [MBProgressHUD showText:[responseObject objectForKey:@"Message"]];
            }
            
        } failure:^(NSError *error) {
            
            [MBProgressHUD hideHUDForView:self.view];
            [MBProgressHUD showText:@"删除失败"];
        }];
        
    }];
    
    [alertController addAction:OKAction];
    
    [self presentViewController:alertController animated:YES completion:nil];
}


#pragma mark 添加体侧模板
-(void)addSide{
    
    [self.courseClassView removeFromSuperview];
    
    AddSideViewController *addSideVC = [[AddSideViewController alloc] init];
    
    [self.navigationController pushViewController:addSideVC animated:YES];
}

#pragma mark Get
-(NSMutableDictionary *)listData{
    
    if (!_listData) {
        
        _listData = [[NSMutableDictionary alloc] init];
    }
    
    return _listData;
}

-(void)dealloc{
    
    [NotificationCenter removeObserver:self];
}

@end
